﻿#region Usings

using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Configuration;
using System.Web;

#endregion

namespace Rail.Net.Common.MEF
{
    /// <summary>
    ///   Inherit this to satisfy imports...
    ///   Or just implement similar functionality if you do not want to inherit...
    /// 
    ///   Xlent Technology: Uffe Björklund
    ///   DateTime: 2011-04-13 19:43
    /// </summary>
    public abstract class Composable
    {
        protected Composable()
        {
            DirectoryCatalogs = new List<string>();

            AggregateCatalog = new AggregateCatalog();

            //Create the catalog to look for plugins in...
            var pluginsFolder = VirtualPathUtility.ToAbsolute(ConfigurationManager.AppSettings.Get("MefDirectoryCatalog"));
            AddDirectoryCatalog(pluginsFolder);

            //Add the catalog to the hostcatalog...                        
            Compose();
        }

        protected CompositionContainer CompositionContainer { get; set; }
        protected AggregateCatalog AggregateCatalog { get; set; }
        protected IList<string> DirectoryCatalogs { get; set; }

        protected void AddDirectoryCatalog(string catalog)
        {
            DirectoryCatalogs.Add(catalog);
        }

        public void Compose()
        {
            //Add Catalogs
            foreach (var directoryCatalog in DirectoryCatalogs)
            {
                AggregateCatalog.Catalogs.Add(new DirectoryCatalog(directoryCatalog));
            }

            //Create compositioncontainer catalog export/import.
            CompositionContainer = new CompositionContainer(AggregateCatalog);

            //And... Compose it... :)              
            CompositionContainer.ComposeParts(this);
        }
    }
}